|
|
|
|
|
|
|
The Inner Life of Stack Frames |
|
|
|
|
|
|
|
|
Let's review what we know about calling functions in DLLs. In order to call a function, an application does the following: |
|
|
|
|
|
|
|
|
1. Pushes parameters onto the stack |
|
|
|
|
|
|
|
|
2. Pushes the return address onto the stack |
|
|
|
|
|
|
|
|
3. Allocates space on the stack for local variables |
|
|
|
|
|
|
|
|
These steps are reversed when the called function returns. |
|
|
|
|
|
|
|
|
This raises an interesting question: Which function is responsible for each of these steps, the calling function or the called function? |
|
|
|
|
|
|
|
|
Obviously, the calling function must push parameters onto the stack. After all, the whole idea of function parameters is to allow a calling function to pass information to the called function. |
|
|
|
|
|
|
|
|
But in the case of multiple parameters, which ones go on the stack first? Are parameters pushed onto the stack from right to left or left to right? |
|
|
|
|
|
|
|
|
It is also plain to see that the calling function must push the return address onto the stack. In reality, this is handled by the CPU itself when it transfers control to the called function. |
|
|
|
|
|
|
|
|
The called function knows what it needs in the way of local variables, so it must allocate space on the stack for these variables. |
|
|
|
|
|
|
|
|
On the return side, similar issues arise. The called function must pop the local variables from the stack, since it knows how much space it allocated. But either function can pop the parameters from the stack, since both the calling function and the called function must know the function parameters. |
|
|
|
|
|
|
|
|
So we're left with two questions: |
|
|
|
|
|
|
|
|
In what order are parameters pushed onto the stack? |
|
|
|
|
|
|
|
|
Which function pops the parameters from the stack? |
|
|
|
|
|
|
|
|
In one sense, it does not matterboth approaches are valid. But it is absolutely critical that the calling function and the called function are compatible with each other. If one pushes function parameters left to right and the other right to left, each function will see the parameters as reverseda sure road to a program error. If both functions try to pop the parameters from the stack, the stack will become corrupt and probably lead to an application crash when the calling function tries to return to the next higher level. |
|
|
|
|
|
|
|
|
The set of standards that specifies exactly how a function is called is referred to as the "calling convention." The calling convention that is used when Visual Basic calls a DLL or Win32 API function is called the "stdcall" (for standard call) calling convention. If your DLL does not use this calling convention, you cannot |
|
|
|
|
|